<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="质检任务单号" prop="taskNo">
        <el-input v-model="queryParams.taskNo" placeholder="请输入质检任务单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="质检来源类型" prop="sourceType">
        <el-select v-model="queryParams.sourceType" placeholder="请选择质检来源类型" filterable clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUALITY_SOURCE_TYPE)" :key="dict.value"
                     :label="dict.label"
                     :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="来源单号" prop="sourceNo">
        <el-input v-model="queryParams.sourceNo" placeholder="请输入来源单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="物料编码" prop="materialNo">
        <el-input v-model="queryParams.materialNo" placeholder="请输入物料编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="工序编号" prop="procedureCode">
        <el-input v-model="queryParams.procedureCode" placeholder="请输入工序编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="工序名称" prop="procedureName">
        <el-input v-model="queryParams.procedureName" placeholder="请输入工序名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="质检方案编码" prop="schemeCode">
        <el-input v-model="queryParams.schemeCode" placeholder="请输入质检方案编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="质检方案名称" prop="schemeName">
        <el-input v-model="queryParams.schemeName" placeholder="请输入质检方案名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="质检方式" prop="schemeMethod">
        <el-select v-model="queryParams.schemeMethod" placeholder="请选择质检方式" filterable style="width: 100%">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SCHEME_METHOD)" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="质检类型" prop="schemeType">
        <el-select v-model="queryParams.schemeType" placeholder="请选择质检类型" filterable style="width: 100%">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SCHEME_TYPE)" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUALITY_STATUS)" :key="dict.value" :label="dict.label"
                     :value="parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input v-model="queryParams.batchNo" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['quality:inspection-scheme-task:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['quality:inspection-scheme-task:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['quality:inspection-scheme-task:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column label="质检任务单号" align="center" prop="taskNo" width="200" show-overflow-tooltip/>
      <el-table-column label="质检来源类型" align="center" prop="sourceTypeName" width="180">
        <template v-slot="scope">
          {{ getDictDataLabel(DICT_TYPE.QUALITY_SOURCE_TYPE, scope.row.sourceType) }}
        </template>
      </el-table-column>
      <el-table-column label="来源单号" align="center" prop="sourceNo" width="180"/>
      <el-table-column label="物料编码" align="center" prop="materialNo"  width="150" show-overflow-tooltip/>
      <el-table-column label="物料名称" align="center" prop="materialName" width="150" show-overflow-tooltip/>
      <el-table-column label="工序编号" align="center" prop="procedureCode" width="150"/>
      <el-table-column label="工序名称" align="center" prop="procedureName"  width="150" show-overflow-tooltip/>
      <el-table-column label="质检方案编码" align="center" prop="schemeCode"  width="150" show-overflow-tooltip/>
      <el-table-column label="质检方案名称" align="center" prop="schemeName" width="150" show-overflow-tooltip/>
      <el-table-column label="质检方式" align="center" prop="schemeMethod" width="150">
        <template v-slot="scope">
          {{ getDictDataLabel(DICT_TYPE.SCHEME_METHOD, scope.row.schemeMethod) }}
        </template>
      </el-table-column>
      <el-table-column label="质检类型" align="center" prop="schemeType" width="150">
        <template v-slot="scope">
          {{ getDictDataLabel(DICT_TYPE.SCHEME_TYPE, scope.row.schemeType) }}
        </template>
      </el-table-column>
      <el-table-column label="巡检间隔(min)" align="center" prop="intervalTime" width="120"/>
      <el-table-column label="抽检比例/数量" align="center" prop="samplingRatio" width="120"/>
      <el-table-column label="质检原因" align="center" prop="qualityReason" width="150">
        <template v-slot="scope">
          {{ getDictDataLabel(DICT_TYPE.QUALITY_REASON, scope.row.qualityReason) }}
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status" width="150">
        <template v-slot="scope">
          {{ getDictDataLabel(DICT_TYPE.QUALITY_STATUS, scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="已完结时间" align="center" prop="finishTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.finishTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="batchNo" width="150"/>
      <el-table-column label="质检总数" align="center" prop="totalQuantity" width="150"/>
      <el-table-column label="合格率" align="center" prop="passRate" width="150"/>
      <el-table-column label="合格数量" align="center" prop="passQuantity" width="150"/>
      <el-table-column label="不合格数量" align="center" prop="failQuantity" width="120"/>
      <el-table-column label="不合格率" align="center" prop="failRate" width="150"/>
      <el-table-column label="不合格原因" align="center" prop="schemeTaskRemark" width="120"/>
      <el-table-column label="返工数量" align="center" prop="reworkQuantity" width="150"/>
      <el-table-column label="报废数量" align="center" prop="scrapQuantity" width="150"/>
      <el-table-column label="让步接收数量" align="center" prop="compromiseQuantity" width="120"/>
      <el-table-column label="审核报废数量" align="center" prop="auditorScrapQuantity" width="120"/>
      <el-table-column label="审核合格数量" align="center" prop="auditorPassQuantity" width="120"/>
      <el-table-column label="审核人名称" align="center" prop="auditorName" width="120"/>
      <el-table-column label="审核备注" align="center" prop="auditorRemark" width="120"/>
      <el-table-column label="有效状态" align="center" prop="effectiveStatus" width="150">
        <template v-slot="scope">
          {{ getDictDataLabel(DICT_TYPE.COMMON_STATUS, scope.row.effectiveStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="无效原因" align="center" prop="invalidReason" width="150"/>
      <el-table-column label="备注" align="center" prop="remark" width="150"/>
      <el-table-column label="创建者" align="center" prop="creator" width="150"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="resultEntry(scope.row.id)"
                     >{{ scope.row.status == 1 ? '查看结果' : '结果录入' }}
          </el-button>
          <el-button size="mini" type="text" :icon="scope.row.status == 1 ? 'el-icon-view' : 'el-icon-edit'" 
                     @click="openForm(scope.row.id, scope.row.status == 1)"
                     v-hasPermi="['quality:inspection-scheme-task:update']">{{ scope.row.status == 1 ? '查看' : '修改' }}
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['quality:inspection-scheme-task:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <InspectionSchemeTaskForm ref="formRef" @success="getList" :viewMode.sync="viewMode"/>

    <!-- 结果录入对话框 -->
    <el-dialog
      title="质检结果录入"
      :visible.sync="resultEntryDialogVisible"
      width="95%"
      :close-on-click-modal="false"
      :before-close="closeResultEntryDialog"
    >
      <el-form :model="resultEntryForm" ref="resultEntryForm" label-width="120px" :disabled="isViewMode">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="合格数量" prop="passQuantity">
              <el-input-number v-model="resultEntryForm.passQuantity" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="不合格数量" prop="failQuantity">
              <el-input-number v-model="resultEntryForm.failQuantity" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报废数量" prop="scrapQuantity">
              <el-input-number v-model="resultEntryForm.scrapQuantity" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="让步接收数量" prop="compromiseQuantity">
              <el-input-number v-model="resultEntryForm.compromiseQuantity" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="不合格原因" prop="schemeTaskRemark">
          <el-input v-model="resultEntryForm.schemeTaskRemark" type="textarea" :rows="2" placeholder="请输入不合格原因"/>
        </el-form-item>

        <!-- 质检项列表 -->
        <el-form-item label="质检项详情" prop="itemList">
          <div v-if="resultEntryForm.itemList && resultEntryForm.itemList.length > 0">
            <el-table :data="resultEntryForm.itemList" style="width: 100%;" height="400">
                <el-table-column label="质检项名称" prop="itemName" width="150">
                  <template v-slot="scope">
                    {{ scope.row.itemName || '质检项 ' + (scope.$index + 1) }}
                  </template>
                </el-table-column>
                <el-table-column label="质检标准" prop="itemStandard" width="200">
                  <template v-slot="scope">
                    {{ scope.row.itemStandard || '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="单位" prop="unit" width="100">
                  <template v-slot="scope">
                    {{ scope.row.unit || '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="质检项分类" align="center" prop="itemType" width="120">
                  <template v-slot="scope">
                    <span>{{ getDictDataLabel(DICT_TYPE.QUALITY_INSPECTION_SCHEME_ITEM_TYPE, scope.row.itemType) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="数值类型" align="center" prop="itemDataType" width="100">
                  <template v-slot="scope">
                    {{ getMapLabel(scope.row.itemDataType, itemDataTypeMap) }}
                  </template>
                </el-table-column>
                <el-table-column label="录入方式" align="center" prop="inputMethod" width="100">
                  <template v-slot="scope">
                    {{ getMapLabel(scope.row.inputMethod, inputMethodMap) }}
                  </template>
                </el-table-column>
                <el-table-column label="标准值" align="center" prop="otherDefect" width="100"></el-table-column>
                <el-table-column label="上公差" align="center" prop="upperValue" width="80"></el-table-column>
                <el-table-column label="下公差" align="center" prop="lowerValue" width="80"></el-table-column>
                <el-table-column label="下警戒值" align="center" prop="lowerBias" width="90"></el-table-column>
                <el-table-column label="上警戒值" align="center" prop="upperBias" width="90"></el-table-column>
                <el-table-column label="SPC坐标" align="center" prop="excelCoordinate" width="90"></el-table-column>
                <el-table-column label="检验默认值" align="center" prop="defaultValue" width="100"></el-table-column>
                <el-table-column label="SPC检" align="center" prop="spcInspection" width="80"></el-table-column>
                <el-table-column label="全尺寸检" align="center" prop="fullSizeInspection" width="100"></el-table-column>
                <el-table-column label="全尺寸坐标" align="center" prop="fullSizeCoordinate" width="110"></el-table-column>
                <el-table-column label="量具坐标" align="center" prop="toolCoordinate" width="90"></el-table-column>
                <el-table-column label="文件名称代码" align="center" prop="failNameCode" width="120"></el-table-column>
                <el-table-column label="不良判定方式" align="center" prop="defectMethod" width="120">
                  <template v-slot="scope">
                    {{ getMapLabel(scope.row.defectMethod, defectMethodMap) }}
                  </template>
                </el-table-column>
                <el-table-column label="实际值" width="200" fixed="right">
                  <template v-slot="scope">
                    <el-input-number v-model="scope.row.realValue" :min="0" style="width: 100%;" :disabled="isViewMode"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="是否合格" width="200" fixed="right">
                  <template v-slot="scope">
                    <el-select v-model="scope.row.isPass" placeholder="请选择" style="width: 100%;" :disabled="isViewMode">
                      <el-option label="合格" :value="1"></el-option>
                      <el-option label="不合格" :value="0"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="不良原因" width="200" fixed="right">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.realReasons" placeholder="请输入不良原因" :disabled="isViewMode || scope.row.isPass !== 0"></el-input>
                  </template>
                </el-table-column>
              </el-table>
          </div>
          <div v-else style="text-align: center; color: #909399; padding: 20px 0;">暂无质检项</div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeResultEntryDialog">取消</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="submitResultEntry" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  /* el-table相关样式已由Element UI默认提供，无需额外样式 */
</style>

<script>
import * as InspectionSchemeTaskApi from '@/api/quality/inspectionschemetask';
import InspectionSchemeTaskForm from './InspectionSchemeTaskForm.vue';

export default {
  name: "InspectionSchemeTask",
  components: {
    InspectionSchemeTaskForm,
  },
  data() {
    return {
      resultEntryData:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 质检任务列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 结果录入数据
      resultEntryData:[],
      // 映射变量
      itemDataTypeMap: {
        'NUMBER': '数值',
        'STRING': '文本',
        'BOOLEAN': '布尔值'
      },
      inputMethodMap: {
        'MANUAL': '手动录入',
        'AUTO': '自动采集'
      },
      defectMethodMap: {
        'RANGE': '范围判定',
        'SPECIFIC': '指定值判定',
        'PATTERN': '模式判定'
      },
      // 结果录入表单数据
      resultEntryForm: {
        id: '',
        passQuantity: 0,
        failQuantity: 0,
        scrapQuantity: 0,
        compromiseQuantity: 0,
        schemeTaskRemark: '',
        itemList: []
      },
      // 结果录入弹框显示状态
      resultEntryDialogVisible: false,
      // 提交中状态
      submitting: false,
      // 是否为查看模式
      isViewMode: false,
      // 表单查看模式
      viewMode: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        taskNo: null,
        sourceType: null,
        sourceTypeName: null,
        sourceNo: null,
        inspectionSchemeId: null,
        materialId: null,
        materialNo: null,
        materialName: null,
        processId: null,
        procedureCode: null,
        procedureName: null,
        schemeCode: null,
        schemeName: null,
        schemeMethod: null,
        schemeType: null,
        status: null,
        batchNo: null,
        effectiveStatus: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async resultEntry(e){
       const res = await InspectionSchemeTaskApi.getInspectionSchemeTask(e);
       // 设置是否为查看模式
       this.isViewMode = res.data.status === 1;
       // 初始化表单数据
       this.resultEntryForm = {
         id: res.data.id,
         passQuantity: res.data.passQuantity || 0,
         failQuantity: res.data.failQuantity || 0,
         scrapQuantity: res.data.scrapQuantity || 0,
         compromiseQuantity: res.data.compromiseQuantity || 0,
         schemeTaskRemark: res.data.schemeTaskRemark || '',
         itemList: res.data.itemList || []
       };

       // 为每个item添加默认值和确保必填字段
       this.resultEntryForm.itemList.forEach(item => {
         if (item.realValue === undefined) item.realValue = '';
         if (item.isPass === undefined) item.isPass = 0;
         if (item.realReasons === undefined) item.realReasons = '';
       });

       // 显示弹框
       this.resultEntryDialogVisible = true;
     },

     // 获取映射标签
     getMapLabel(value, map) {
       return map[value] || '-';
     },

     // 提交结果录入
     async submitResultEntry() {
       // 表单验证
       const hasEmptyField = this.resultEntryForm.itemList.some(item =>
         !item.realValue ||
         item.isPass === undefined ||
         (item.isPass === 0 && !item.realReasons)
       );

       if (hasEmptyField) {
         this.$modal.msgError('请填写所有必填字段（实际值、是否合格，不合格时需填写不良原因）');
         return;
       }

       try {
         this.submitting = true;
         // 调用API提交数据
         await InspectionSchemeTaskApi.resultsInput(this.resultEntryForm);
         this.$modal.msgSuccess('录入成功');
         // 关闭弹框
         this.resultEntryDialogVisible = false;
         // 刷新列表
         this.getList();
       } catch (error) {
         this.$modal.msgError('录入失败，请重试');
         console.error('Result entry failed:', error);
       } finally {
         this.submitting = false;
       }
     },

     // 关闭结果录入弹框
     closeResultEntryDialog() {
       this.resultEntryDialogVisible = false;
       // 重置查看模式
       this.isViewMode = false;
     },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await InspectionSchemeTaskApi.getInspectionSchemeTaskPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id, isView = false) {
      this.viewMode = isView;
      this.$refs["formRef"].open(id, isView);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除质检任务编号为"' + id + '"的数据项?')
      try {
        await InspectionSchemeTaskApi.deleteInspectionSchemeTask(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除质检任务 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await InspectionSchemeTaskApi.deleteInspectionSchemeTaskList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有质检任务数据项?');
      try {
        this.exportLoading = true;
        const data = await InspectionSchemeTaskApi.exportInspectionSchemeTaskExcel(this.queryParams);
        this.$download.excel(data, '质检任务.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  }
};
</script>
<style scoped lang="scss">
:deep(.el-input__inner:disabled),
:deep(.el-select__inner:disabled),
:deep(.el-date-editor .el-input__inner:disabled),
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #F9F9F9 !important;
  color: #333 !important;
  border-color: #DCDFE6 !important;
}

:deep(.vue-treeselect--disabled) {
  background-color: #F9F9F9 !important;
  .vue-treeselect__control {
    background-color: #F9F9F9 !important;
    color: #333 !important;
  }
}
</style>